//
//  HMComposeTextView.swift
//  WeiBo
//
//  Created by Feng on 2017/6/13.
//  Copyright © 2017年 feng. All rights reserved.
//

import UIKit

class HMComposeTextView: UITextView {

    //MARK: --懒加载控件
    private lazy var placeHolderLabel: UILabel =
    {
        let label = UILabel(fontSize: 13, textColor: UIColor.lightGray)
        label.text = "请输入微博内容"
        label.numberOfLines = 0
        
        return label
    }()
    
    //MARK: --重写didSet方法
    var placeHolder: String?
    {
        didSet {
            placeHolderLabel.text = placeHolder
        }
    }
    
    override var font: UIFont?
    {
        didSet {
            placeHolderLabel.font = font
        }
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //MARK: --设置界面及约束
    private func setupUI()
    {
        //注册通知
        NotificationCenter.default.addObserver(self, selector: #selector(textChanged), name: NSNotification.Name.UITextViewTextDidChange, object: nil)
        
        addSubview(placeHolderLabel)
        
        placeHolderLabel.translatesAutoresizingMaskIntoConstraints = false
        
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 7))
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 5))
        //textView继承于scrollView,所以不能设置右边约束
        addConstraint(NSLayoutConstraint(item: placeHolderLabel, attribute: .width, relatedBy: .equal, toItem: self, attribute: .width, multiplier: 1, constant: -10))
    }
    
    //监听通知方法
    @objc private func textChanged()
    {
        placeHolderLabel.isHidden = self.hasText
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
